package com.fs.erp.api.basedata.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.erp.api.basedata.entity.ProductCategory;
import com.fs.erp.api.basedata.enums.ProductCategoryNodeType;
import com.fs.erp.api.basedata.mappers.ProductCategoryMapper;
import com.fs.erp.api.basedata.service.ProductCategoryService;
import com.fs.erp.api.basedata.vo.product.category.CreateProductCategoryVo;
import com.fs.erp.api.basedata.vo.product.category.UpdateProductCategoryVo;
import com.fs.erp.common.constants.StringPool;
import com.fs.erp.common.exceptions.impl.DefaultClientException;
import com.fs.erp.common.utils.CollectionUtil;
import com.fs.erp.common.utils.StringUtil;
import com.fs.erp.mybatis.service.system.IRecursionMappingService;
import com.fs.erp.web.utils.ApplicationUtil;
import com.fs.erp.web.utils.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@Repository
public class ProductCategoryServiceImpl extends BaseMpServiceImpl<ProductCategoryMapper, ProductCategory>
        implements ProductCategoryService {
    @Autowired
    private IRecursionMappingService recursionMappingService;

    /**
     *查找
     * @return
     */
    @Override
    public List<ProductCategory> getAllProductCategory() {
        return getBaseMapper().getAllProductCategory();
    }

    /**
     * 修改
     * @param vo
     */
    @Override
    public void updateCategory(UpdateProductCategoryVo vo) {
        ProductCategory category=getBaseMapper().selectById(vo.getId());

        //code是否重复
        Wrapper<ProductCategory> checkCodeWrapper = Wrappers.lambdaQuery(ProductCategory.class)
                .eq(ProductCategory::getCode,vo.getCode()).ne(ProductCategory::getId,category.getId());
        if (getBaseMapper().selectCount(checkCodeWrapper)>0){
            throw new DefaultClientException("编号重复");
        }

        //name是否重复
        Wrapper<ProductCategory> checkNameWrapper = Wrappers.lambdaQuery(ProductCategory.class)
                .eq(ProductCategory::getName,vo.getName()).ne(ProductCategory::getId,category.getId());
        if (getBaseMapper().selectCount(checkNameWrapper)>0){
            throw new DefaultClientException("名称重复");
        }

        Wrapper<ProductCategory> updateWrapper=Wrappers.lambdaUpdate(ProductCategory.class)
                .set(ProductCategory::getCode,vo.getCode()).set(ProductCategory::getName,vo.getName())
                .set(ProductCategory::getDescription,StringUtil.isBlank(vo.getDescription())?StringPool.EMPTY_STR:vo.getDescription())
                .set(ProductCategory::getAvailable,vo.getAvailable())
                .eq(ProductCategory::getId,category.getId());

        update(updateWrapper);

        if (!vo.getAvailable()) {
            if (category.getAvailable()) {
                //如果是停用 子节点全部停用
                List<String> childrenIds = recursionMappingService.getNodeChildIds(category.getId(),
                        ApplicationUtil.getBean(ProductCategoryNodeType.class));
                if (!CollectionUtil.isEmpty(childrenIds)) {
                    this.batchUnable(childrenIds);
                }
            }
        } else {
            if (!category.getAvailable()) {
                //如果是启用 父节点全部启用
                List<String> parentIds = recursionMappingService.getNodeParentIds(category.getId(),
                        ApplicationUtil.getBean(ProductCategoryNodeType.class));
                if (!CollectionUtil.isEmpty(parentIds)) {
                    this.batchEnable(parentIds);
                }
            }
        }
    }


    @Override
    public ProductCategory selectCategoryById(String id) {
        return getBaseMapper().selectById(id);
    }

    /**
     * 根据ID停用
     * @param ids
     */
    @Override
    public void batchUnable(Collection<String> ids) {
        if (CollectionUtil.isEmpty(ids)){
            return;
        }

        List<String> batchIds=new ArrayList<>();
        for (String id:ids){
            List<String> nodeChildIds=recursionMappingService.getNodeChildIds(id
                    ,ApplicationUtil.getBean(ProductCategoryNodeType.class));
            if(CollectionUtil.isEmpty(nodeChildIds)){
                continue;
            }

            batchIds.addAll(nodeChildIds);
        }

        batchIds.addAll(ids);

        Wrapper<ProductCategory> updateWrapper=Wrappers.lambdaUpdate(ProductCategory.class)
                .set(ProductCategory::getAvailable,Boolean.FALSE)
                .in(ProductCategory::getId,batchIds);
        update(updateWrapper);
    }

    /**
     * 根据ID启用
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchEnable(Collection<String> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return;
        }

        List<String> batchIds = new ArrayList<>();
        for (String id : ids) {
            List<String> nodeParentIds = recursionMappingService.getNodeParentIds(id,
                    ApplicationUtil.getBean(ProductCategoryNodeType.class));
            if (CollectionUtil.isEmpty(nodeParentIds)) {
                continue;
            }

            batchIds.addAll(nodeParentIds);
        }

        batchIds.addAll(ids);

        Wrapper<ProductCategory> updateWrapper = Wrappers.lambdaUpdate(ProductCategory.class)
                .set(ProductCategory::getAvailable, Boolean.TRUE).in(ProductCategory::getId, batchIds);
        update(updateWrapper);
    }

    /**
     * 添加
     * @param vo
     * @return
     */
    @Override
    public String createCategory(CreateProductCategoryVo vo) {

        //查询code是否重复
        Wrapper<ProductCategory> checkCodeWrapper=Wrappers.lambdaQuery(ProductCategory.class)
                .eq(ProductCategory::getCode,vo.getCode());
        if (getBaseMapper().selectCount(checkCodeWrapper)>0){
            throw new DefaultClientException("编号已存在");
        }

        //查询name是否重复
        Wrapper<ProductCategory> checkNameWrapper=Wrappers.lambdaQuery(ProductCategory.class)
                .eq(ProductCategory::getName,vo.getName());
        if (getBaseMapper().selectCount(checkNameWrapper)>0){
            throw new DefaultClientException("名称已存在");
        }


        ProductCategory category=new ProductCategory();
        category.setId(IdUtil.getId());
        category.setCode(vo.getCode());
        category.setName(vo.getName());
        //检验是否为空
        if (!StringUtil.isBlank(vo.getParentId())){
            category.setParentId(vo.getParentId());
        }
        category.setAvailable(Boolean.TRUE);//状态
        category.setDescription(vo.getDescription());//备注


        getBaseMapper().insert(category);
        //保存递归信息
        this.saveRecursion(category.getId(),category.getParentId());
        return category.getId();
//        return getBaseMapper().createCategory(vo);
    }

    /**
     * 保存递归信息
     * @param id
     * @param parentId
     */
    private void saveRecursion(String id, String parentId) {
        if (!StringUtil.isBlank(parentId)){
            List<String> parentIds=recursionMappingService.getNodeParentIds(parentId, ApplicationUtil.getBean(ProductCategoryNodeType.class));
            if (CollectionUtil.isEmpty(parentIds)){
                parentIds=new ArrayList<>();
            }
            parentIds.add(parentId);

            recursionMappingService.saveNode(id,ApplicationUtil.getBean(ProductCategoryNodeType.class),parentIds);
        }else {
            //保存节点递归信息
            recursionMappingService.saveNode(id,ApplicationUtil.getBean(ProductCategoryNodeType.class));
        }
    }


}
